package com.lry.crawlers.video.processor;

import com.lry.crawlers.video.entity.VideoVariable;
import com.lry.crawlers.video.service.VideoService;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.*;
import java.util.regex.Pattern;

public class VideoProcessor implements PageProcessor {

    public VideoVariable videoVariable;

    public VideoService videoService;

    public VideoProcessor(){
    }

    public VideoProcessor(VideoVariable videoVariable, VideoService videoService){
        this.videoVariable = videoVariable;
        this.videoService = videoService;
    }



    private Site site = Site.me()
            .setSleepTime(1)//采集间隔时间
            .setTimeOut(1000*10)//超时时间
            .setRetrySleepTime(3000)//重试时间
            .setRetryTimes(3);//重试次数

    public Site getSite() {
        return site;
    }
    

    //解析页面
    public void process(Page page) {

        String url = page.getUrl().toString();
        String[] titless = videoVariable.getVideoTitle().split("-!-");
        List<String> videoTitlee = page.getHtml().xpath(titless[0]).regex(titless.length != 1 ? titless[1] : ".+").all();
        String[] titlesss = videoVariable.getTitle().split("-!-");
        List<String> titleee = page.getHtml().xpath(titlesss[0]).regex(titlesss.length != 1 ? titlesss[1] : ".+").all();

        //视频搜索
        if(videoTitlee.size()!=0){
            List<String> title = new ArrayList<String>();
            try {
                //获取视频信息：title，desc,author,videoType,cover,VideoUrl,VideoId
                String[] titles = videoVariable.getVideoTitle().split("-!-");
                title = page.getHtml().xpath(titles[0]).regex(titles.length != 1 ? titles[1] : ".+").all();
            }catch (Exception e){}

            //通过视频标签判断搜索内容是否存在
            if(title.size()!=0){
                String[] videoUrls = videoVariable.getVideoUrl().split("-!-");
                String[] pageUrls = videoVariable.getPage().split("-!-");
                List<String> videoUrl = page.getHtml().xpath(videoUrls[0]).regex(videoUrls.length !=1 ? videoUrls[1] : ".+").all();
                String pageUrl = page.getHtml().xpath(pageUrls[0]).regex(pageUrls.length !=1 ? pageUrls[1] : ".+").get();
                //获取视频章节与内容的对应的chapterId,并处理无域名url
                if(!videoUrl.get(0).contains("http")){
                    List<String> videoUrll = new ArrayList<>();
                    videoUrl.forEach(str -> {
                        videoUrll.add(videoVariable.getProtocol()+"://"+ videoVariable.getUrl()+str);
                    });
                    videoUrl = videoUrll;
                }
                List<Integer> duplicates = videoService.removeDuplicates(title);
                for (int i : duplicates) {
                    videoUrl.set(i,null);
                }
                while (videoUrl.remove(null));
                if (videoUrl.size() != 0) {
                    //把视频链接加入爬取列表
                    page.addTargetRequests(videoUrl);
                }
                //把视频下一页加入爬取列表
                if (pageUrl != null) {
                    if (pageUrl.contains("http")) {
                    }else if(pageUrl.contains("/")){
                        pageUrl = videoVariable.getProtocol() + "://" + videoVariable.getUrl() + pageUrl;
                    }else if(!pageUrl.contains("javascript")){
                        pageUrl = url + pageUrl;
                    }
                    page.addTargetRequest(pageUrl);
                }
            }
        }
        //视频章节
        else if(titleee.size()!=0){
            //获取视频章节信息：chapterTitle，chapterUrl，chapterId
            //获取视频信息：title，desc,author,videoType,cover,VideoUrl,VideoId
            String[] titles = videoVariable.getTitle().split("-!-");
            String[] descs = videoVariable.getDescs().split("-!-");
            String[] authors = videoVariable.getAuthor().split("-!-");
            String[] videoTypes = videoVariable.getVideoType().split("-!-");
            String[] covers = videoVariable.getCover().split("-!-");
            String[] chapterTitles = videoVariable.getChapterTitle().split("-!-");
            String[] chapterUrls = videoVariable.getChapterUrl().split("-!-");
            String[] updateTimes = videoVariable.getUpdateTime().split("-!-");
            List<String> title = page.getHtml().xpath(titles[0]).regex(titles.length !=1 ? titles[1] : ".+").all();
            List<String> desc = page.getHtml().xpath(descs[0]).regex(descs.length !=1 ? descs[1] : ".+").all();
            List<String> author = page.getHtml().xpath(authors[0]).regex(authors.length !=1 ? authors[1] : ".+").all();
            List<String> videoType = page.getHtml().xpath(videoTypes[0]).regex(videoTypes.length !=1 ? videoTypes[1] : ".+").all();
            List<String> cover = page.getHtml().xpath(covers[0]).regex(covers.length !=1 ? covers[1] : ".+").all();
            List<String> chapterTitle = page.getHtml().xpath(chapterTitles[0]).regex(chapterTitles.length !=1 ? chapterTitles[1] : ".+").all();
            List<String> chapterUrl = page.getHtml().xpath(chapterUrls[0]).regex(chapterUrls.length !=1 ? chapterUrls[1] : ".+").all();
            List<String> updateTime = page.getHtml().xpath(updateTimes[0]).regex(updateTimes.length !=1 ? updateTimes[1] : ".+").all();
            if(chapterTitles.length ==3){
                String[] splitTitl = chapterTitles[2].split(",");
                if(splitTitl.length ==1){
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),chapterTitle.size());
                }else{
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),Integer.parseInt(splitTitl[1]));

                }
            }
            if(chapterUrls.length == 3){
                String[] splitUrls = chapterUrls[2].split(",");
                if(splitUrls.length ==1){
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),chapterUrl.size());
                }else{
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),Integer.parseInt(splitUrls[1]));
                }
            }

            //获取对应的videoId
            String videoId = Pattern.compile("[^0-9]").matcher(url).replaceAll("").trim();
            //判断是否存在
            if (title.size() == 0) {
                title.add(" ");
            }
            if (author.size() == 0) {
                author.add(" ");
            }
            if (videoType.size() == 0) {
                videoType.add(" ");
            }
            if (cover.size() == 0) {
                cover.add(" ");
            }
            if (updateTime.size() == 0) {
                updateTime.add(" ");
            }
            if (desc.size() == 0) {
                desc.add(" ");
            }
            if (chapterTitle.size() == 0) {
                chapterTitle.add(" ");
            }
            if (chapterUrl.size() == 0) {
                chapterUrl.add(" ");
            }
            if(!cover.get(0).contains("http")){
                cover.set(0,videoVariable.getProtocol() + "://" + videoVariable.getUrl() + cover.get(0));
            }
            boolean duplicate = videoService.removeDuplicate(title.get(0));
            if(!duplicate) {
                //创建储存Map数据，用于业务处理
                Map<String, Object> chapterMap = new HashMap<>();
                chapterMap.put("key", "videoChapter");
                chapterMap.put("title", title.get(0));
                chapterMap.put("desc", desc.get(0));
                chapterMap.put("author", author.get(0));
                chapterMap.put("updateTime", updateTime.get(0));
                chapterMap.put("videoType", videoType.get(0));
                chapterMap.put("cover", cover.get(0));
                chapterMap.put("chapterTitle", chapterTitle);
                chapterMap.put("chapterUrl", chapterUrl);
                chapterMap.put("videoId", videoId);
                chapterMap.put("updateUrl", url);
                chapterMap.put("id", videoVariable.getId());
                //提交数据，给Pipeline处理
                page.putField("data", chapterMap);
            }
        }
    }
}

